<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" type="text/css" href="css/template.css">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>HappyMeal Management System</title>
</head>

<body>
<div id='all'>
  <div id='all-wrap'> 
    
    <!--header begin-->
    <div id='wrap-header'>
      <?php
			include 'header.php';
			//Forbid Non-admin from adding new user
			if($_SESSION['is_admin'] == 0){
				//Auto redirect
				header("Refresh: 2;url=main.php");
   				die("You do not have the permission to edit user. Click <a href='partner.php'>here</a> if your browser cannot redirect");
			}
		?>
    </div>
    <!--header end--> 
    
    <!--wrap-body begin-->
    <div id='wrap-body'> 
      <!-- wrap-content begin-->
      <div id='wrap-content'> 
        <!-- nav begin -->
        <div id='nav' style="padding-left:30px;">
          <h4>Current : <a href='main.php'>Main</a>
            <?php include 'nav_png.php'; ?>
            User</h4>
        </div>
        <!-- nav END --> 
        
        <!-- wrap-search begin -->
        <div id='wrap-search'> 
          <!-- No search module implemented for search--> 
        </div>
        <!-- wrap-search end --> 
        
        <!-- check if it is add or edit or view or delete -->
        <?php
			
				$show_alert = true;
				if(isset($_POST['user_add'])){
					// user_add
					$telephone 			= $_POST['telephone'];
					$imei				= $_POST['imei'];
					$name 				= $_POST['name'];
					$description		= $_POST['description'];
					
					//Upload profile picture
					//Extracted from w3schools.com
					$allowedExts = array("gif", "jpeg", "jpg", "png");
					$temp = explode(".", $_FILES["profile"]["name"]);
					$extension = end($temp);
					$profile_picture_directory = "android/profile/";

					if (((strtolower($_FILES["profile"]["type"]) == "image/gif")
								|| (strtolower($_FILES["profile"]["type"]) == "image/jpeg")
								|| (strtolower($_FILES["profile"]["type"]) == "image/jpg")
								|| (strtolower($_FILES["profile"]["type"]) == "image/pjpeg")
								|| (strtolower($_FILES["profile"]["type"]) == "image/x-png")
								|| (strtolower($_FILES["profile"]["type"]) == "image/png"))
								&& ($_FILES["profile"]["size"] < 1000000)
								&& in_array($extension, $allowedExts)){
  						if ($_FILES["profile"]["error"] > 0){
    						//echo "Return Code: " . $_FILES["profile"]["error"] . "<br>";
    					}else{
    						/*
							echo "Upload: " . $_FILES["profile"]["name"] . "<br>";
							echo "Type: " . $_FILES["profile"]["type"] . "<br>";
							echo "Size: " . ($_FILES["profile"]["size"] / 1024) . " kB<br>";
							echo "Temp file: " . $_FILES["profile"]["tmp_name"] . "<br>";
							*/
							if(file_exists($profile_picture_directory . $_FILES["profile"]["name"])){
								echo $_FILES["profile"]["name"]." already exists. ";
							}else{
								//Generate random name
								$random_name = generateRandomString();
								move_uploaded_file($_FILES["profile"]["tmp_name"],$profile_picture_directory.$random_name.".".$extension);
								//echo "Stored in: " .$profile_picture_directory. $_FILES["profile"]["name"];
								$profile_picture 	= $profile_picture_directory.$random_name.".".$extension;
							}
						}
					}else{
					  echo "Invalid file";
					}		
					// Extracted from w3schools.com END
					

					//$coupon				= $_POST['coupon'];
					//Datetime format : date ("Y-m-d H:i:s");
					$last_login			= "0000-00-00 00:00:00";
					$register_date		= date("Y-m-d H:i:s");
					$is_blocked			= $_POST['is_blocked'];
					$is_activated		= $_POST['is_activated'];

					//Prevent Double entering
					$sql_check = "SELECT * FROM user WHERE telephone='$telephone'";
					$sql_check_result = mysql_query($sql_check);
					if(mysql_num_rows($sql_check_result) < 1){
     					//Partner does not exist
						$sql_add = "INSERT INTO user(telephone,imei,name,description,profile_picture,last_login,register_date,is_blocked,is_activated) VALUES ";
						$sql_add = $sql_add."('$telephone','$imei','$name','$description','$profile_picture','$last_login','$register_date','$is_blocked','$is_activated')";
						$sql_add_result = mysql_query($sql_add);
						if($sql_add_result){
							$message = "Successfully add new user";
						}else{
							$message = "Fail to add new user - SQL ERROR";
						}
   					}else{
						//Partner already exists
						$message = "Fail to add new user - USER ALREADY EXISTS";
					}
				}else if(isset($_POST['user_edit'])){
					$id					= $_POST['id'];
					$telephone 			= $_POST['telephone'];
					$imei				= $_POST['imei'];
					$name 				= $_POST['name'];
					$description		= $_POST['description'];
					
					//Upload profile picture
					//Extracted from w3schools.com
					$allowedExts = array("gif", "jpeg", "jpg", "png");
					$temp = explode(".", $_FILES["profile"]["name"]);
					$extension = end($temp);
					$profile_picture_directory = "android/profile/";

					$update_profile_picture = false;
					if($_FILES["profile"]["name"] != ""){
						//echo "update profile - not null name<Br>";
						if (((strtolower($_FILES["profile"]["type"]) == "image/gif")
								|| (strtolower($_FILES["profile"]["type"]) == "image/jpeg")
								|| (strtolower($_FILES["profile"]["type"]) == "image/jpg")
								|| (strtolower($_FILES["profile"]["type"]) == "image/pjpeg")
								|| (strtolower($_FILES["profile"]["type"]) == "image/x-png")
								|| (strtolower($_FILES["profile"]["type"]) == "image/png"))
									&& ($_FILES["coupon"]["size"] < 1000000)
									&& in_array(strtolower($extension), $allowedExts)){
							echo "update profile - passed test<Br>";
							if ($_FILES["profile"]["error"] > 0){
								//echo "Return Code: " . $_FILES["profile"]["error"] . "<br>";
							}else{
								/*
								echo "Upload: " . $_FILES["profile"]["name"] . "<br>";
								echo "Type: " . $_FILES["profile"]["type"] . "<br>";
								echo "Size: " . ($_FILES["profile"]["size"] / 1024) . " kB<br>";
								echo "Temp file: " . $_FILES["profile"]["tmp_name"] . "<br>";
								*/
								if(false && file_exists($profile_picture_directory . $_FILES["profile"]["name"])){
									echo $_FILES["profile"]["name"]." already exists. ";
								}else{
									$random_name = generateRandomString();
									move_uploaded_file($_FILES["profile"]["tmp_name"],$profile_picture_directory.$random_name.".".$extension);
									//echo "Stored in: " .$profile_picture_directory. $_FILES["profile"]["name"];
									echo "update profile <Br>";
									$update_profile_picture = true;
									
									$profile_picture 	= $profile_picture_directory.$random_name.".".$extension;
								}
							}
						}else{
						  echo "Invalid Profile Picture";
						}
						
						// Extracted from w3schools.com END
					}

					//$coupon				= $_POST['coupon'];
					//Datetime format : date ("Y-m-d H:i:s");
					//$last_login			= "0000-00-00 00:00:00";
					//$register_date		= date("Y-m-d H:i:s");
					$is_blocked			= $_POST['is_blocked'];
					$is_activated		= $_POST['is_activated'];
					
					//NOT YET FIXED
					
					$sql_edit = "UPDATE user SET ";
					$sql_edit = $sql_edit."telephone='$telephone',imei='$imei',name='$name',name='$name',description='$description',";
					if($update_profile_picture){
						$sql_edit = $sql_edit."profile_picture='$profile_picture',";
					}
					$sql_edit = $sql_edit."is_blocked='$is_blocked',is_activated='$is_activated' ";
					$sql_edit = $sql_edit."WHERE id='$id'";
					if(mysql_query($sql_edit)){
						//successful
						$message = "Successfully update user with id = ".$id;
						//echo "success";
					}else{
						$message = "Fail to update user with id = ".$id;
						//echo "fail";
					}
					
				}else if(isset($_POST['user_delete'])){
					// partner_delete
					$id = $_POST['id'];
					$sql_delete01 = "DELETE FROM user WHERE id='$id'";
					if(mysql_query($sql_delete01)){
						//successful
						$message = "Successfully delete user with id = ".$id;
					}else{
						$message = "Fail to delete user with id = ".$id;
					}
				}else{
					// view all category only
					$show_alert = false;
				}
				
				if($show_alert){
	            	echo "<script type='text/javascript'>confirm(";
					echo json_encode($message);
					echo ");</script>";
				}
			?>
        
        <!-- Add button -->
        <h4 align="right" style="padding-right:20px;">
          <?php
				if($_SESSION['is_admin'] == 1){
            		echo "<a href='user_add.php'>Add a new user</a>";
				}
            ?>
        </h4>
        
        <!-- Print table of categories -->
        <?php
				if($_SESSION['is_admin'] == 1){
					// Display all restaurants when the user is an administrator
					$sql_view = "SELECT * FROM user ORDER BY telephone ASC";
				}
				
				// Execute Query
				$result_view = mysql_query($sql_view);
				
				echo "<table id='partner_table'>";
				echo "<tr>";
				echo "<th style='width: 5%;'>ID</th>";
				echo "<th style='width: 25%;'>Telephone</th>";
				echo "<th style='width: 30%;'>IMEI</th>";
				echo "<th style='width: 15%;'>Last Login</th>";
				echo "<th style='width: 10%;'>Blocked?</th>";
				echo "<th style='width: 10%;'>Activated?</th>";
				echo "<th style='width: 5%;'>Edit</th>";
				echo "</tr>";
				while($row = mysql_fetch_array($result_view)){
					$id 		= $row['id'];
					$telephone	= $row['telephone'];
					$imei		= $row['imei'];
					$last_login = $row['last_login'];
					$is_blocked	= $row['is_blocked'];
					$is_activated= $row['is_activated'];
					
					//Get Passcode
					$query_passcode = "SELECT * FROM user_verify WHERE user='$id'";
					$query_passcode_result = mysql_query($query_passcode);
					$query_passcode_result_row = mysql_fetch_array($query_passcode_result);
					$passcode = $query_passcode_result_row['passcode'];
					
					echo "<tr>";
					echo "<td align='center'>".$id."</td>";
					echo "<td align='center'>".$telephone."</td>";
					echo "<td align='center'>".$imei."<br /> SMS : ".$passcode."</td>";
					echo "<td align='center'>".$last_login."</td>";
					if($is_blocked == 0){
						//not blocked
						echo "<td align='center'>No</td>";
					}else{
						//blocked
						echo "<td align='center'>Yes</td>";
					}
					if($is_activated == 0){
						//not admin
						echo "<td align='center'>No</td>";
					}else{
						//is admin
						echo "<td align='center'>Yes</td>";
					}
				//	echo "<td align='center'><a href=''>Edit</a></td>";
					echo "<td align='center'><input type='button' name='user_edit_btn' value='Edit' onclick='window.location=\"user_edit.php?id=".$id."\";' />";
					echo "</tr>";
				}
				echo "</table>";
			?>
      </div>
      <!-- wrap-content end--> 
      
    </div>
    <!--wrap-body end--> 
    
    <!--wrap-footer begin-->
    <div id='wrap-footer'>
      <?php
			include 'footer.php';
		?>
    </div>
    <!--wrap-footer end--> 
    
  </div>
  <!--all-wrap end--> 
</div>
<!--all end-->
</body>
</html>